<template>
  <div class="grade-statistics">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>成绩统计</span>
          <el-button type="primary" @click="refreshData" :loading="loading" icon="Refresh">刷新数据</el-button>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="总考试次数" :value="statistics.totalExams" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="平均分" :value="statistics.averageScore" :precision="1" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="及格率" :value="statistics.passRate" suffix="%" :precision="1" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="最高分" :value="statistics.maxScore" />
        </el-col>
      </el-row>
      
      <el-divider />
      
      <div class="chart-container">
        <h4>成绩分布图</h4>
        <div v-if="chartData.length > 0" ref="chartRef" style="height: 400px;"></div>
        <el-empty v-else description="暂无成绩分布数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import { examRecordApi } from '@/api/examRecords'
import './GradeStatistics.scss'

const route = useRoute()

const statistics = ref({
  totalExams: 0,
  averageScore: 0,
  passRate: 0,
  maxScore: 0
})

const chartData = ref<{ scoreRange: string; count: number }[]>([])
const chartRef = ref<HTMLElement | null>(null)
const loading = ref(false)
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    updateChart()
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize)
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || chartData.value.length === 0) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: chartData.value.map(item => item.scoreRange),
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '人数'
      }
    ],
    series: [
      {
        name: '人数',
        type: 'bar',
        barWidth: '60%',
        data: chartData.value.map(item => item.count),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

// 加载统计数据
const loadStatistics = async (examId: number) => {
  try {
    loading.value = true
    
    // 调用后端接口获取统计数据
    const res = await examRecordApi.getExamStatistics(examId)
    
    // 处理返回的数据
    const data = res.data
    
    // 计算及格率
    const passRate = data.totalCount ? ((data.passCount || 0) / data.totalCount) * 100 : 0
    
    statistics.value = {
      totalExams: data.totalCount || 0,
      averageScore: data.avgScore !== null ? Number(data.avgScore.toFixed(1)) : 0,
      passRate: Number(passRate.toFixed(1)),
      maxScore: data.maxScore || 0
    }
    
    // 处理成绩分布数据
    chartData.value = data.scoreDistribution || []
    
    // 更新图表
    await nextTick()
    updateChart()
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 如果后端接口调用失败，使用模拟数据
    const mockData = {
      totalCount: 125,
      avgScore: 78.5,
      passCount: 95,
      maxScore: 98,
      scoreDistribution: [
        { scoreRange: '0-9', count: 2 },
        { scoreRange: '10-19', count: 3 },
        { scoreRange: '20-29', count: 5 },
        { scoreRange: '30-39', count: 8 },
        { scoreRange: '40-49', count: 12 },
        { scoreRange: '50-59', count: 15 },
        { scoreRange: '60-69', count: 20 },
        { scoreRange: '70-79', count: 25 },
        { scoreRange: '80-89', count: 22 },
        { scoreRange: '90-100', count: 13 }
      ]
    }
    
    const passRate = (mockData.passCount / mockData.totalCount) * 100
    
    statistics.value = {
      totalExams: mockData.totalCount,
      averageScore: Number(mockData.avgScore.toFixed(1)),
      passRate: Number(passRate.toFixed(1)),
      maxScore: mockData.maxScore
    }
    
    chartData.value = mockData.scoreDistribution
    
    // 更新图表
    await nextTick()
    updateChart()
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = async () => {
  const examId = getExamIdFromRoute()
  await loadStatistics(examId)
}

// 获取路由参数中的examId
const getExamIdFromRoute = (): number => {
  return Number(route.params.examId) || 1; // 默认examId为1
}

onMounted(async () => {
  const examId = getExamIdFromRoute()
  await loadStatistics(examId)
  await nextTick()
  initChart()
})

onUnmounted(() => {
  // 清理事件监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  margin-top: 20px;
  
  h4 {
    margin-bottom: 15px;
  }
}
</style>